package cn.com.server.controller.orderListManager;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import cn.com.server.common.AjaxCodeUtil;
import cn.com.server.common.AjaxObject;
import cn.com.server.entity.OrderList;
import cn.com.server.service.MongoDBService;

@Controller
@RequestMapping("/orderList")
public class OrderListController {
	
	@Autowired
    private MongoDBService mongoDBService;
	
	@RequestMapping("/orderListView")
	public String orderListView(HttpServletRequest request, HttpServletResponse response) {
		return "/orderListManager/orderListView";
	}
	
	@RequestMapping("/getOrderList")
	@ResponseBody
	public AjaxObject getOrderList(HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		@SuppressWarnings("unused")
		List<OrderList> orderList = mongoDBService.findAll(OrderList.class);
		Query query = new Query();
		Page<OrderList> pp = mongoDBService.getPagination(OrderList.class,query, 1, 10);
		AjaxObject ajaxObject = AjaxCodeUtil.getAjaxObject("success");
		ajaxObject.setData(pp);
		return ajaxObject;
	}
	

	@RequestMapping("/save")
	@ResponseBody
	public AjaxObject saveOrderList(OrderList orderList,HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		try {
			if(null != orderList.getId()){
				mongoDBService.save(orderList);
			}else{
				orderList.setId(Long.valueOf(mongoDBService.getId(OrderList.class.getName())));
				mongoDBService.insert(orderList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxCodeUtil.getAjaxObject("success");
	}


	@RequestMapping("/delete")
	@ResponseBody
	public AjaxObject delete(String ids,HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		String[] array = ids.split(",");
		if(null == array){
			return AjaxCodeUtil.getAjaxObject("deleteException");
		}
		if(array.length == 1){
			OrderList orderList = mongoDBService.findOne(OrderList.class, new Query(Criteria.where("_id").is(ids)));
			if(!mongoDBService.remove(orderList)) {
				return AjaxCodeUtil.getAjaxObject("success");
			}
		}else{
			List<OrderList> oderLists = mongoDBService.find(OrderList.class, new Query(Criteria.where("_id").in(Arrays.asList(ids))));
			for(OrderList orderList : oderLists){
				mongoDBService.remove(orderList);
			}
		}
		return AjaxCodeUtil.getAjaxObject("success");
	}
	
}
